package com.android.smdonkeyditu;
import java.util.ArrayList;
import java.util.List;

import android.location.Location;
import android.os.Bundle;
import android.content.Context;
import android.content.Intent;


import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.GeoPoint;
import com.baidu.mapapi.ItemizedOverlay;
import com.baidu.mapapi.LocationListener;
import com.baidu.mapapi.MapActivity;
import com.baidu.mapapi.MapView;

import com.baidu.mapapi.OverlayItem;

import android.widget.Toast;
import com.baidu.mapapi.MKSearch;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.DialogInterface;
import android.graphics.Point;
import android.graphics.drawable.Drawable;

import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;

public  class smdonkeyditu extends MapActivity {
    /** Called when the activity is first created. */
	LocationListener mLocationListener = null;//create时注册此listener，Destroy时需要Remove
	GeoPoint objpoint=null;	
	boolean IsGPSlocated=false;	
	Drawable marker=null;//地图上覆盖物的风格对象
	String strLog=null;//记录地图上显示的经纬度信息变量
	public static MapView mMapView = null;	// 地图View
	boolean isSatelite = false;	// 是否显示卫星图层
	MKSearch mSearch = null;	// 搜索模块，也可去掉地图模块独立使用
	public static BMapManager mBMapMan = null;   
    protected void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mBMapMan = new BMapManager(getApplication());
        mBMapMan.init("67294E369219ABBB28811626BE568C40C8F3310D", null);//"67294E369219ABBB28811626BE568C40C8F3310D"为API接口许可码
        mBMapMan.start();
        super.initMapActivity(mBMapMan);       
        mMapView = (MapView) findViewById(R.id.bmapView);       
        mMapView.setBuiltInZoomControls(true);  //设置启用内置的缩放控件 
        mMapView.setSatellite(false);
        try// 设定GPS的响应  
        {
  	    mLocationListener = new LocationListener(){
			public void onLocationChanged(Location location) {
			if(IsGPSlocated==false)
			{
				if(location != null){
					objpoint=new GeoPoint((int)(location.getLatitude()* 1E6),(int) (location.getLongitude()* 1E6));
					
					strLog = String.format("您当前所在的位置坐标是：\r\n\n" +
							"纬度:%f \r" +
							"经度:%f",
							location.getLatitude(),location.getLongitude());//要显示的经纬度信息					
					smdonkeyditu.mMapView.getController().animateTo(objpoint);
					smdonkeyditu.mMapView.getController().setZoom(16);
					//将GPS定位得到的位置在地图上显示出来
					marker = getResources().getDrawable(R.drawable.donkeysmall);  //得到需要标在地图上的资源
  					marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker
  							.getIntrinsicHeight());   //为maker定义位置和边界
  					smdonkeyditu.mMapView.getOverlays().clear();
  					smdonkeyditu.mMapView.getOverlays().add(new AddOverlay(marker,smdonkeyditu.this,objpoint,""));
					//显示经纬度信息在地图下方
  					Toast.makeText(smdonkeyditu.this, strLog, Toast.LENGTH_LONG).show();
					IsGPSlocated=true;
				}
			}
		         
		}
      };}
        catch(Exception ex)
        {
        	 new AlertDialog.Builder(this)
             .setTitle("GPS设备提示")
             .setMessage("GPS没有信号")
             .setPositiveButton("确定", new DialogInterface.OnClickListener() {
              
              @Override
              public void onClick(DialogInterface arg0, int arg1) {
             	 
              }
             }).setNegativeButton("取消", new DialogInterface.OnClickListener() {         
              @Override
              public void onClick(DialogInterface arg0, int arg1) {
              }
             })
             .show();
        }
         
    
    }        
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {   
	       menu.add(0, 0, 0, "关于我们");	       
	       menu.add(0, 1, 1, "地址查找");
	    //   Resources res = getBaseContext().getResources();
	      // sub.setIcon(res.getDrawable(R.drawable.iconmarka));
	       //menu.setHeaderIcon(res.getDrawable(R.drawable.icon));	      
	       menu.add(0, 2, 2, "GPS定位");
	       menu.add(0, 3, 3, "路线查找");
	       menu.add(0, 4, 4, "卫星地图");
	       menu.add(0, 5, 5, "退出");	       
	       return super.onCreateOptionsMenu(menu); 
	}
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
       switch(item.getItemId())
       {
          case 0:
            openAboutDialog();
            break;
          case 1:      	  
        	// 设定地址查找的响应
      		Intent intent = null;
    		intent = new Intent(smdonkeyditu.this, GeoCodeSeacher.class);
    		startActivity(intent);
            break;
          case 2:      	  
          	// 设定GPS的响应
        	  if(IsGPSlocated==true)
        	  {
        	 
        	 smdonkeyditu.mMapView.getController().animateTo(objpoint);
			 smdonkeyditu.mMapView.getController().setZoom(16);
      		 smdonkeyditu.mMapView.getOverlays().clear();
      		 smdonkeyditu.mMapView.getOverlays().add(new AddOverlay(marker,smdonkeyditu.this,objpoint,""));
      		 Toast.makeText(smdonkeyditu.this, strLog, Toast.LENGTH_LONG).show();
        	  }
             break;
          case 3:      	  
          	// 设定地址查找的响应
        	Intent intent1 = null;
      		intent1 = new Intent(smdonkeyditu.this, RouteSearcher.class);
      		startActivity(intent1);
              break;
          case 4:
    	    if(isSatelite==false)
    	    {
    	        mMapView.setSatellite(true);
    	        isSatelite=true;
    	    }
    	    else
    	    {
    		    mMapView.setSatellite(false);
    		    isSatelite=false;
    	    }
    	    break;
          case 5:
        	ExitNowDialog();
            isSatelite=false;
            break;
       }  
       return super.onOptionsItemSelected(item);
    }   
    public class AddOverlay extends ItemizedOverlay<OverlayItem>{
		private List<OverlayItem> mGeoList = new ArrayList<OverlayItem>();

		public AddOverlay(Drawable marker, Context context, GeoPoint pt, String title) {
			super(boundCenterBottom(marker));
			
			mGeoList.add(new OverlayItem(pt, title, null));

			populate();
		}

		@Override
		protected OverlayItem createItem(int i) {
			return mGeoList.get(i);
		}

		@Override
		public int size() {
			return mGeoList.size();
		}

		@Override
		public boolean onSnapToItem(int i, int j, Point point, MapView mapview) {
			Log.e("ItemizedOverlayDemo","enter onSnapToItem()!");
			return false;
		}
	}
    
    
    
    private void ExitNowDialog(){
        new AlertDialog.Builder(this)
        .setTitle("退出提示")
        .setMessage("确定要退出驴游地图？")
        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
         
         @Override
         public void onClick(DialogInterface arg0, int arg1) {
        	 isSatelite=false;        	 
        	 ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE); 
        	 manager.killBackgroundProcesses(getPackageName());
        	 finish();
         }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {         
         @Override
         public void onClick(DialogInterface arg0, int arg1) {
         }
        })
        .show();
     } 
    private void openAboutDialog(){
       new AlertDialog.Builder(this)
       .setTitle("关于")
       .setMessage("驴游地图  版权所有©地信091班")
       .setPositiveButton("确定", new DialogInterface.OnClickListener() {
        
        @Override
        public void onClick(DialogInterface arg0, int arg1) {
        }
       }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
        
        @Override
        public void onClick(DialogInterface arg0, int arg1) {
        }
       })
       .show();
    } 
    @Override
	protected void onPause() {
		if (mBMapMan != null) 
		{       
			mBMapMan.getLocationManager().removeUpdates(mLocationListener);
			mBMapMan.stop();   
			
		}    
		super.onPause();
	}
	@Override
	protected void onResume() {
		mBMapMan.getLocationManager().requestLocationUpdates(mLocationListener);
		mBMapMan.start();
		super.onResume();
	}
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			// 确认对话框
			final AlertDialog isExit = new AlertDialog.Builder(this).create();
			// 对话框标题
			isExit.setTitle("退出提示");
			// 对话框消息
			isExit.setMessage("确定要退出驴游地图吗?");
			// 实例化对话框上的按钮点击事件监听
			DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					switch (which) {
					case AlertDialog.BUTTON1:// 点击"确认"按钮退出程序						
						 NotificationManager notificationManager = (NotificationManager) smdonkeyditu.this 
		                    .getSystemService(NOTIFICATION_SERVICE); 
						 	notificationManager.cancel(0);
						 	isSatelite=false;
						 	 ActivityManager manager = (ActivityManager)getSystemService(ACTIVITY_SERVICE); 
				        	 manager.killBackgroundProcesses(getPackageName());
				        	 finish();
							finish();//结束地图界面
							System.exit(0);//完全退出系统
						break;
					case AlertDialog.BUTTON2://点击 "取消"按钮取消退出
						isExit.cancel();
						break;
					default:
						break;
					}
				}
			};
			// 注册监听
			isExit.setButton("确定", listener);
			isExit.setButton2("取消", listener);
			// 显示对话框
			isExit.show();
			return false;
		}
		return false;
	}
	
	/*
	 //获取手机系统版本号
	 private static int getSystemVersion(){
		return android.os.Build.VERSION.SDK_INT;
		}
	*/
	
}
